package com.educate.common.filter;


import com.educate.common.utils.exception.AppException;
import com.educate.common.web.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Log4j2
public class DefaultErrorHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R defaultErrorHandler(Throwable e) {
        if (e.getMessage() != null) {
            int startIndex = e.getMessage().indexOf(AppException.class.getName());
            if (startIndex >= 0) {
                int lastIndex = e.getMessage().indexOf(System.lineSeparator());
                if (lastIndex >= 0) {
                    log.info(e.getMessage());
                    return R.error(e.getMessage().substring(startIndex + AppException.class.getName().length(), lastIndex));
                }
            }
        }
        if (e instanceof AppException && e.getCause() == null) {
            log.info(e.getMessage());
        } else {
            e.printStackTrace();
        }
        String message = e.getMessage();
        if (message == null || message.length() > 60) {
            message = "业务繁忙";
        }
        return R.error(message);
    }
}
